package com.zhihuichongcheng.application.ui.task.adapter.holder;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.smartlib.cmnObject.dialog.DialogOnClick;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.StringUtil;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.bean.task.TaskBean;
import com.zhihuichongcheng.application.bean.task.TaskPriority;
import com.zhihuichongcheng.application.bean.task.TaskType;
import com.zhihuichongcheng.application.ui.im.activity.UserListActivity;
import com.zhihuichongcheng.application.ui.task.ContentEditActivity;
import com.zhihuichongcheng.application.ui.task.SubTaskListActivity;
import com.zhihuichongcheng.application.ui.task.TaskDetailActivity;
import com.zhihuichongcheng.application.util.CollectionUtils;
import com.zhihuichongcheng.application.util.StringUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * task content Created by LK on 2017/1/9.
 */
public class TaskContentHolder extends BaseHolder
        implements View.OnClickListener, TimePickerDialog.OnTimeSetListener {
    private LinearLayout taskTypeLayout;
    private View itemTaskName, itemTaskContent, itemToUser, itemTaskLv, itemTaskDate, itemTaskLocation, itemTaskCCUsers, itemSubTask;

    private TextView mTvTitle, mTvContent, mTvExecutors, mTvDate, mTvTime, mTvTaskLv, mTvTaskLocation, mTvCCUsers, mTvSubTask;
    private TaskBean taskBean = new TaskBean();
    private BaseActivity mCurrentActivity = null;

    private List<ImageView> taskTypes = new ArrayList<>();

    public TaskContentHolder(BaseActivity activity, View itemView) {
        this(itemView, activity);
        this.mCurrentActivity = activity;
    }

    private TaskContentHolder(View itemView, BaseActivity activity) {
        super(itemView, activity);
        taskTypeLayout = (LinearLayout) itemView.findViewById(R.id.layout_task_type);

        itemTaskName = itemView.findViewById(R.id.ll_task_name);
        itemTaskContent = itemView.findViewById(R.id.ll_task_content);
        itemToUser = itemView.findViewById(R.id.ll_task_executors);
        itemTaskLv = itemView.findViewById(R.id.ll_task_lv);
        itemTaskDate = itemView.findViewById(R.id.ll_task_date);
        itemTaskLocation = itemView.findViewById(R.id.ll_task_location);
        itemTaskCCUsers = itemView.findViewById(R.id.ll_task_cc_users);
        itemSubTask = itemView.findViewById(R.id.ll_sub_task);

        mTvTitle = (TextView) itemView.findViewById(R.id.task_title);
        mTvContent = (TextView) itemView.findViewById(R.id.task_content);
        mTvExecutors = (TextView) itemView.findViewById(R.id.task_executors);
        mTvDate = (TextView) itemView.findViewById(R.id.task_date);
        mTvTime = (TextView) itemView.findViewById(R.id.task_time);
        mTvTaskLv = (TextView) itemView.findViewById(R.id.task_lv);
        mTvTaskLocation = (TextView) itemView.findViewById(R.id.task_location);
        mTvCCUsers = (TextView) itemView.findViewById(R.id.task_cc_users);
        mTvSubTask = (TextView) itemView.findViewById(R.id.tv_sub_task);

    }

    /**
     * 设置数据
     */
    public void setData() {
        // 设置数据
        setDataToViews();
        //判断显隐性
        setViewsShowOrNot();
        //绑定监听器
        bindListener();
    }

    private void setDataToViews() {
        //任务类型
        setTaskType();
        //任务标题
        mTvTitle.setText(taskBean.getTitle());
        //任务执行者
        mTvExecutors.setText(taskBean.getExecutorNicknames());
        //任务日期
        mTvDate.setText(taskBean.getDate());
        //任务时间
        mTvTime.setText(taskBean.getTime());
        //任务优先级
        mTvTaskLv.setText(taskBean.getPriorityName());
        //任务地址
        mTvTaskLocation.setText(taskBean.getLocation());
        //任务内容
        mTvContent.setText(taskBean.getContent());
        // 子任务
        mTvSubTask.setText("子任务 " + taskBean.getSubTaskFinish() + "/" + taskBean.getSubTaskCount());
        //任务参与者
        String ccUserNickNames = taskBean.getCCUserNicknames();
        if (!StringUtils.isEmpty(ccUserNickNames))
            mTvCCUsers.setText(taskBean.getCCUserNicknames());
    }

    private void setViewsShowOrNot() {
        if (createTask() || canEditTask()) {
            //地理位置
            itemTaskLocation.setVisibility(View.VISIBLE);
            itemView.findViewById(R.id.line_location).setVisibility(View.VISIBLE);
            //任务内容
            itemTaskContent.setVisibility(View.VISIBLE);
            itemView.findViewById(R.id.line_content).setVisibility(View.VISIBLE);
        } else {
            //地理位置
            itemTaskLocation.setVisibility(StringUtils.isEmpty(taskBean.getLocation()) ? View.GONE : View.VISIBLE);
            itemView.findViewById(R.id.line_location).setVisibility(StringUtils.isEmpty(taskBean.getLocation()) ? View.GONE : View.VISIBLE);
            //任务内容
            itemTaskContent.setVisibility(StringUtils.isEmpty(taskBean.getContent()) ? View.GONE : View.VISIBLE);
            itemView.findViewById(R.id.line_content).setVisibility(StringUtils.isEmpty(taskBean.getContent()) ? View.GONE : View.VISIBLE);
        }
        //子任务
        itemSubTask.setVisibility(createTask() ? View.GONE : View.VISIBLE);
        itemView.findViewById(R.id.line_subtask).setVisibility(createTask() ? View.GONE : View.VISIBLE);
    }

    private void bindListener() {
        itemTaskName.setOnClickListener(this);
        itemTaskContent.setOnClickListener(this);
        itemToUser.setOnClickListener(this);
        mTvTime.setOnClickListener(this);
        itemTaskLv.setOnClickListener(this);
        itemTaskDate.setOnClickListener(this);
        itemTaskLocation.setOnClickListener(this);
        itemTaskCCUsers.setOnClickListener(this);
        itemSubTask.setOnClickListener(this);
    }

    private void setTaskType() {
        taskTypeLayout.removeAllViews();
        CollectionUtils.iterator(TaskBean.taskTypeList, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                setItemTypeToLayout((TaskType) data);
                return false;
            }
        });
    }

    private boolean createTask() {
        return taskBean.getTaskId() <= 0;
    }

    private boolean canEditTask() {
        return !createTask() && taskBean.getCreateUserId() == Integer.parseInt(app.getUser().getUserId());
    }

    public void setItemTypeToLayout(final TaskType taskType) {
        View itemView = LayoutInflater.from(taskTypeLayout.getContext())
                .inflate(R.layout.view_task_type, taskTypeLayout, false);
        final ImageView imgSelector = (ImageView) itemView.findViewById(R.id.img_task_type);
        TextView tvType = (TextView) itemView.findViewById(R.id.tv_task_type);
        imgSelector.setImageResource(taskBean.getType() == taskType.getId() ?
                R.drawable.ic_check_select :
                R.drawable.ic_check_normal);
        tvType.setText(taskType.getName());
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (taskBean.getTaskId() > 0 && taskBean.getCreateUserId() != Integer.parseInt(app.getUser().getUserId()))
                    return;
                resetTaskType();
                taskBean.setType(taskType.getId());
                imgSelector.setImageResource(R.drawable.ic_check_select);
            }
        });
        taskTypes.add(imgSelector);
        taskTypeLayout.addView(itemView);
    }

    private void resetTaskType() {
        CollectionUtils.iterator(taskTypes, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                ((ImageView) data).setImageResource(R.drawable.ic_check_normal);
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_task_name:
                Bundle bundleName = new Bundle();
                bundleName.putString(ContentEditActivity.EXTRA_TITLE, "任务名称");
                bundleName.putString(ContentEditActivity.EXTRA_HINT, "请输入任务名称");
                bundleName.putString(ContentEditActivity.EXTRA_CONTENT_DEFAULT, taskBean.getTitle());
                if (taskBean.getTaskId() > 0) {
                    bundleName.putBoolean(ContentEditActivity.EXTRA_EDITABLE, taskBean.getCreateUserId() == Integer.parseInt(app.getUser().getUserId()));
                }
                startActivityForResult(ContentEditActivity.class, TaskDetailActivity.REQUEST_CODE_RESET_TITLE, bundleName);
                break;
            case R.id.ll_task_content:
                Bundle bundleContent = new Bundle();
                bundleContent.putString(ContentEditActivity.EXTRA_TITLE, "任务内容");
                bundleContent.putString(ContentEditActivity.EXTRA_HINT, "请输入任务内容");
                bundleContent.putString(ContentEditActivity.EXTRA_CONTENT_DEFAULT, taskBean.getContent());
                if (taskBean.getTaskId() > 0) {
                    bundleContent.putBoolean(ContentEditActivity.EXTRA_EDITABLE, taskBean.getCreateUserId() == Integer.parseInt(app.getUser().getUserId()));
                }
                startActivityForResult(ContentEditActivity.class, TaskDetailActivity.REQUEST_CODE_RESET_CONTENT, bundleContent);
                break;
            case R.id.ll_task_executors:
                if (taskBean.getTaskId() > 0 && taskBean.getCreateUserId() != Integer.parseInt(app.getUser().getUserId()))
                    return;
                Bundle bundleExecutor = new Bundle();
                bundleExecutor.putString(UserListActivity.EXTRA_TITLE, "执行者");
                bundleExecutor.putBoolean(UserListActivity.EXTRA_FOR_RESULT, true);
                startActivityForResult(UserListActivity.class,
                        TaskDetailActivity.REQUEST_CODE_RESET_EXECUTOR,
                        bundleExecutor);
                break;
            case R.id.ll_task_cc_users:
                if (taskBean.getTaskId() > 0 && taskBean.getCreateUserId() != Integer.parseInt(app.getUser().getUserId()))
                    return;
                Bundle bundleCCUsers = new Bundle();
                bundleCCUsers.putString(UserListActivity.EXTRA_TITLE, "参与者");
                bundleCCUsers.putBoolean(UserListActivity.EXTRA_FOR_RESULT, true);
                startActivityForResult(UserListActivity.class,
                        TaskDetailActivity.REQUEST_CODE_RESET_CC_USERS,
                        bundleCCUsers);
                break;
            case R.id.ll_task_date:
                if (taskBean.getTaskId() > 0 && taskBean.getCreateUserId() != Integer.parseInt(app.getUser().getUserId()))
                    return;
                DialogUtil.showDatePick(itemView.getContext(), new DialogOnClick<String>() {
                    @Override
                    public void onClick(String s) {
                        String[] date = s.split("-");
                        String year = date[0];
                        String month = date[1];
                        String day = date[2];
                        taskBean.setDate(year + "年" + month + "月" + day + "日");
                        mTvDate.setText(taskBean.getDate());
                    }
                });
                break;
            case R.id.task_time:
                if (taskBean.getTaskId() > 0 && taskBean.getCreateUserId() != Integer.parseInt(app.getUser().getUserId()))
                    return;
                Calendar time = Calendar.getInstance();
                TimePickerDialog timePickerDialog = TimePickerDialog.newInstance(
                        this,
                        time.get(Calendar.HOUR_OF_DAY),
                        time.get(Calendar.MINUTE),
                        true);
                timePickerDialog.show(mCurrentActivity.getFragmentManager(), "TimePickerDialog");
                break;
            case R.id.ll_task_lv:
                if (taskBean.getTaskId() > 0 && taskBean.getCreateUserId() != Integer.parseInt(app.getUser().getUserId()))
                    return;
                //遍历任务优先级
                final String[] prioritiesStr = new String[TaskBean.taskPriorities.size()];
                CollectionUtils.iterator(TaskBean.taskPriorities, new CollectionUtils.AIIteratorListCallBack() {
                    @Override
                    public boolean callback(Object data, int position) {
                        TaskPriority item = (TaskPriority) data;
                        prioritiesStr[position] = item.getName();
                        return false;
                    }
                });
                new MaterialDialog.Builder(itemView.getContext())
                        .title("任务级别")
                        .items(prioritiesStr)
                        .itemsCallbackSingleChoice(taskBean.getCurrentPriorityIndex(), new MaterialDialog.ListCallbackSingleChoice() {
                            @Override
                            public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                taskBean.setPriority(TaskBean.taskPriorities.get(which).getId());
                                mTvTaskLv.setText(TaskBean.taskPriorities.get(which).getName());
                                return true;
                            }
                        })
                        .show();
                break;
            case R.id.ll_task_location:
                Bundle bundleLocation = new Bundle();
                bundleLocation.putString(ContentEditActivity.EXTRA_TITLE, "位置");
                bundleLocation.putString(ContentEditActivity.EXTRA_HINT, "请输入位置信息");
                bundleLocation.putString(ContentEditActivity.EXTRA_CONTENT_DEFAULT, taskBean.getLocation());
                if (taskBean.getTaskId() > 0) {
                    bundleLocation.putBoolean(ContentEditActivity.EXTRA_EDITABLE, taskBean.getCreateUserId() == Integer.parseInt(app.getUser().getUserId()));
                }
                startActivityForResult(ContentEditActivity.class, TaskDetailActivity.REQUEST_CODE_RESET_LOCATION, bundleLocation);
                break;
            case R.id.ll_sub_task:
                Bundle bundle = new Bundle();
                bundle.putInt(SubTaskListActivity.EXTRA_TASK_ID, taskBean.getTaskId());
                bundle.putString(SubTaskListActivity.EXTRA_TASK_TO_USER_IDS, taskBean.getExecutorUserIds());
                startActivity(SubTaskListActivity.class, bundle);
                break;
        }
    }

    /**
     * 更新task标题
     */
    public void notifyTaskTitle(String title) {
        if (!StringUtil.isEmpty(title))
            taskBean.setTitle(title);
        else
            taskBean.setTitle("");
        mTvTitle.setText(taskBean.getTitle());
    }

    /**
     * 更新task标题
     */
    public void notifyTaskContent(String content) {
        if (!StringUtil.isEmpty(content))
            taskBean.setContent(content);
        else
            taskBean.setContent("");
        mTvContent.setText(taskBean.getContent());
    }

    /**
     * 更新task标题
     */
    public void notifyTaskLocation(String location) {
        if (!StringUtil.isEmpty(location))
            taskBean.setLocation(location);
        else
            taskBean.setLocation("");
        mTvTaskLocation.setText(taskBean.getLocation());
    }

    public void notifyExecutors(List<UserBean> result) {
        taskBean.resetExecutors(result);
        mTvExecutors.setText(taskBean.getExecutorNicknames());
    }

    @Override
    public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
        taskBean.setTime(hourOfDay + " : " + minute + " 截止");
        mTvTime.setText(taskBean.getTime());
    }

    public void notifyCCUsers(List<UserBean> result) {
        taskBean.resetCCUsers(result);
        mTvCCUsers.setText(taskBean.getCCUserNicknames());
    }

    public TaskBean getTaskBean() {
        return taskBean;
    }

    public void setTaskBean(TaskBean taskBean) {
        this.taskBean = taskBean;
    }
}
